using System.Collections;
using System.Collections.Generic;
using BCW.Friends;
using ExitGames.Client.Photon;
using UnityEngine;
using UnityEngine.SceneManagement;

public class controllerConnectPhoton : PhotonMonoMessagesHandler
{
	public enum connectTo
	{
		none = 0,
		quickGame = 1,
		customGame = 2
	}

	public static controllerConnectPhoton thisScript;

	[HideInInspector]
	public List<RoomInfo> filteredRoomList = new List<RoomInfo>();

	public connectTo tekConnect;

	public static TypeGame _chooseTypeGame;

	public static string _chooseNameLevel = string.Empty;

	public string filterForSearchRoom = string.Empty;

	public ManagerScrollButMap managerBigMap;

	public ManagerScrollButMap managerPVPMap;

	[SerializeField]
	private RoomLevels[] Boilers;

	[SerializeField]
	private RoomLevels[] sandboxBoilers;

	public static string _minLeague = "minLeague";

	public static string _maxLeague = "maxLeague";

	public static string _typeGame = "typeGame";

	public static string _nameLevel = "nameLevel";

	public static string _respZone = "respZone";

	public static string _GameStarted = "GameStarted";

	public static string _StartRaceTime = "_StartRaceTime";

	public static string _FinalCountdown = "_FinalCountdown";

	public static string _indexRound = "indexRount";

	public Dictionary<string, string> CarBoiler = new Dictionary<string, string>
	{
		{ "CarBentley", "Boiler_2" },
		{ "CarTruck_NY", "Boiler_2" },
		{ "Car_BMWm3", "Boiler_1" },
		{ "Car_BUGGI", "Boiler_1" },
		{ "CarBunny", "Boiler_1" },
		{ "Car_Cadillac_one", "Boiler_2" },
		{ "CarCamaro", "Boiler_2" },
		{ "car_dodje_Chelendjer", "Boiler_2" },
		{ "CarCube", "Boiler_1" },
		{ "_SantaCarRace", "Boiler_1" },
		{ "_CarSedanRace", "Boiler_1" },
		{ "_CarEscaladeCadillacRace", "Boiler_1" },
		{ "_car_dodje_ChelendjerRace", "Boiler_1" },
		{ "CarEvergreen", "Boiler_1" },
		{ "car_ferrary", "Boiler_2" },
		{ "SantaCar", "Boiler_2" },
		{ "Car_Gelendewagen", "Boiler_2" },
		{ "Car_Hearse", "Boiler_2" },
		{ "CarHummer", "Boiler_2" },
		{ "CarHummer_NY", "Boiler_2" },
		{ "CarSubaru", "Boiler_2" },
		{ "CarSport", "Boiler_2" },
		{ "Car_Countryman", "Boiler_2" },
		{ "CarMini", "Boiler_1" },
		{ "car_MonsterTruck", "Boiler_2" },
		{ "CarMustang", "Boiler_1" },
		{ "Car_RAM_pickup", "Boiler_2" },
		{ "Car_PoliceJeep", "Boiler_2" },
		{ "CarPorshe_911", "Boiler_2" },
		{ "SantaSleigh_NY", "Boiler_2" },
		{ "car_Deathcar", "Boiler_2" },
		{ "car_Nascar", "Boiler_2" },
		{ "Car_Taxi", "Boiler_2" },
		{ "car_ChallengerHemi", "Boiler_2" },
		{ "car_truk", "Boiler_2" },
		{ "Car_Manta", "Boiler_2" },
		{ "car_vaz2104", "Boiler_1" },
		{ "CarHotrod", "Boiler_2" },
		{ "car_ferrary_eyes", "Boiler_2" },
		{ "Car_Impala", "Boiler_2" },
		{ "Car_GhostBusters", "Boiler_2" },
		{ "CarVeyron", "Boiler_2" }
	};

	private int _playerBoiler;

	private int _playerSandboxBoiler;

	public bool changeMap;

	private bool isJoinToRoom;

	private static IEnumerator _moveToGameScene;

	private RoomInfo[] _listRoom;

	public TypeGame chooseTypeGame
	{
		get
		{
			return _chooseTypeGame;
		}
		set
		{
			_chooseTypeGame = value;
		}
	}

	public string chooseNameLevel
	{
		get
		{
			return _chooseNameLevel;
		}
		set
		{
			_chooseNameLevel = value;
		}
	}

	public int playerBoiler
	{
		get
		{
			return _playerBoiler;
		}
	}

	private void Awake()
	{
		thisScript = this;
		InitPlayerBoilersValues();
	}

	public void InitPlayerBoilersValues()
	{
		int currentTier = CupsManager.CurrentTier;
		for (int i = 0; i < Boilers.Length; i++)
		{
			if (Boilers[i].minLvl <= currentTier && currentTier <= Boilers[i].maxLvl)
			{
				_playerBoiler = i;
			}
		}
		for (int j = 0; j < sandboxBoilers.Length; j++)
		{
			if (sandboxBoilers[j].minLvl <= currentTier && currentTier <= sandboxBoilers[j].maxLvl)
			{
				_playerSandboxBoiler = j;
			}
		}
	}

	public void _initializeWorldwide()
	{
		if (LicenseChecker.instance != null)
		{
			LicenseChecker.instance.Start();
		}
		if (!PhotonNetwork.connected)
		{
			if (BCWDebug.isDebugBuild)
			{
				BCWDebug.Log("settings.verConnectPhoton =" + settings.verConnectPhoton);
			}
			PhotonNetwork.ConnectUsingSettings(settings.verConnectPhoton);
			OnReceivedRoomListUpdate();
		}
	}

	private void OnFailedToConnectToPhoton(object parameters)
	{
		BCWDebug.Log("OnFailedToConnectToPhoton. StatusCode: " + parameters);
	}

	private void OnDisconnectedFromPhoton()
	{
		_moveToGameScene = null;
		BCWDebug.Log("Disconnected from Photon.");
	}

	public void OnConnectedToPhoton()
	{
		BCWDebug.Log("OnConnectedToPhotoninit");
	}

	public void OnPhotonInstantiate(PhotonMessageInfo info)
	{
		BCWDebug.Log("OnPhotonInstantiate init" + info.sender);
	}

	public void OnJoinedLobby()
	{
		_moveToGameScene = null;
		PhotonNetwork.player.UpdateProperty(PlayerPropsKeys.playerId, BCWServer.idPlayer);
		if (!changeMap && controllerMenu.thisScript != null)
		{
			thisScript.changeMap = false;
			controllerMenu.thisScript.hideIndicator();
			if (!controllerMenu.thisScript.ClickOnButton)
			{
				tekConnect = connectTo.none;
			}
			if (tekConnect == connectTo.quickGame && !controllerConnectGame.thisScript.ReconnectCanceled)
			{
				ConnectCreate_RandomRoom(chooseTypeGame, chooseNameLevel);
			}
		}
		else if (!changeMap)
		{
		}
		if (thisScript.changeMap && controllerConnectGame.thisScript != null && !controllerConnectGame.thisScript.ReconnectCanceled)
		{
			ConnectCreate_RandomRoom(chooseTypeGame, chooseNameLevel);
		}
	}

	private void OnConnectionFail(DisconnectCause cause)
	{
		BCWDebug.Log("OnConnectionFail");
		if (controllerMenu.thisScript != null)
		{
			controllerMenu.thisScript.hideIndicator();
			_moveToGameScene = null;
		}
	}

	public void OnLeftRoom()
	{
		if (thisScript.changeMap)
		{
			ConnectCreate_RandomRoom(chooseTypeGame, chooseNameLevel);
			_moveToGameScene = null;
		}
	}

	public void LeaveRoom(bool joinRandomroom = true)
	{
		if (joinRandomroom)
		{
			chooseNameLevel = string.Empty;
		}
		controllerConnectGame.reconnectRoom = false;
		thisScript.changeMap = true;
		PhotonNetwork.LeaveRoom();
	}

	private void OnPhotonJoinRoomFailed()
	{
		if (controllerMenu.thisScript != null)
		{
			BCWDebug.Log("OnPhotonJoinRoomFailed");
		}
	}

	public void CreateRandomRoomForChoosedType(TypeGame chooseType)
	{
		ExitGames.Client.Photon.Hashtable hashtable = new ExitGames.Client.Photon.Hashtable();
		hashtable[_typeGame] = (int)chooseType;
		controllerLoadingGame.typeGame = chooseType;
		if (chooseType == TypeGame.race && CarBoiler.ContainsKey(settings.RaceCarName))
		{
			hashtable["Boiler"] = CarBoiler[settings.RaceCarName];
		}
		List<string> list = new List<string>();
		if (ManagerPVPLevels.instance != null)
		{
			foreach (SceneInfo item in ManagerPVPLevels.instance.listSceneName)
			{
				if (item.type == chooseType)
				{
					list = item.nameScene;
					break;
				}
			}
		}
		string text = string.Empty;
		if (list.Count > 0)
		{
			text = list[Random.Range(0, list.Count)];
			hashtable[_nameLevel] = text;
		}
		settings.SetAreaNameForLoading(text);
		createNewRoom(string.Empty, 3, string.Empty, chooseType, text);
	}

	public void ConnectRandomRoom_PVP()
	{
		RoomInfo[] roomList = PhotonNetwork.GetRoomList();
		chooseTypeGame = TypeGame.deathmath;
		List<string> list = new List<string>();
		for (int i = 0; i < roomList.Length; i++)
		{
			if (roomList[i].customProperties["pass"] == string.Empty && (int)roomList[i].customProperties[_typeGame] == (int)chooseTypeGame && 0 < roomList[i].playerCount && roomList[i].playerCount < roomList[i].maxPlayers)
			{
				list.Add(roomList[i].name);
			}
		}
		if (list.Count > 0)
		{
			connectRandomRoom(string.Empty, TypeGame.deathmath);
		}
		else
		{
			OnPhotonRandomJoinFailed();
		}
	}

	public void connectRandomRoom(string nameScene = "", TypeGame needTypeGame = TypeGame.normal)
	{
		changeMap = true;
		chooseNameLevel = nameScene;
		chooseTypeGame = needTypeGame;
		if (IOSInternetConnection.isEnable)
		{
			controllerMenu.thisScript.LoadAllOffline(needTypeGame);
		}
		else if (!PhotonNetwork.connected)
		{
			BCWDebug.Log("_initializeWorldwide");
			tekConnect = connectTo.quickGame;
			_initializeWorldwide();
		}
		else
		{
			ConnectCreate_RandomRoom(needTypeGame, nameScene);
		}
	}

	private void ConnectCreate_RandomRoom(TypeGame modeGame = TypeGame.normal, string nameLevel = "")
	{
		_moveToGameScene = null;
		BCWDebug.Log("ConnectCreate_RandomRoom");
		if (controllerMenu.thisScript != null)
		{
			controllerMenu.thisScript.showIndicator();
		}
		if (PhotonNetwork.inRoom)
		{
			PhotonNetwork.LeaveRoom();
		}
		chooseNameLevel = nameLevel;
		chooseTypeGame = modeGame;
		ExitGames.Client.Photon.Hashtable hashtable = new ExitGames.Client.Photon.Hashtable();
		if (modeGame != TypeGame.race && modeGame != TypeGame.tanks && modeGame != TypeGame.RocketLeague)
		{
			if (nameLevel.Equals("Level1"))
			{
				hashtable["pass"] = string.Empty;
				hashtable[_minLeague] = sandboxBoilers[_playerSandboxBoiler].minLvl.ToString();
				hashtable[_maxLeague] = sandboxBoilers[_playerSandboxBoiler].maxLvl.ToString();
			}
			else
			{
				hashtable["pass"] = string.Empty;
				hashtable[_minLeague] = Boilers[_playerBoiler].minLvl.ToString();
				hashtable[_maxLeague] = Boilers[_playerBoiler].maxLvl.ToString();
			}
		}
		else if ((modeGame == TypeGame.race || modeGame == TypeGame.RocketLeague) && CarBoiler.ContainsKey(settings.RaceCarName))
		{
			hashtable["Boiler"] = CarBoiler[settings.RaceCarName];
		}
		if (!string.IsNullOrEmpty(nameLevel))
		{
			hashtable["nameLevel"] = nameLevel;
		}
		controllerLoadingGame.typeGame = modeGame;
		hashtable[_typeGame] = (int)modeGame;
		if (BCWDebug.isDebugBuild)
		{
			BCWDebug.Log(hashtable.ToStringFull());
		}
		thisScript.changeMap = true;
		StartCoroutine(WateToConnectMasterServer(hashtable));
	}

	private IEnumerator WateToConnectMasterServer(ExitGames.Client.Photon.Hashtable expectedCustomRoomProperties)
	{
		while (PhotonNetwork.connectionStateDetailed != ClientState.ConnectedToMaster && PhotonNetwork.connectionStateDetailed != ClientState.JoinedLobby)
		{
			yield return null;
		}
		isJoinToRoom = PhotonNetwork.JoinRandomRoom(expectedCustomRoomProperties, 0, MatchmakingMode.FillRoom, null, null);
		yield return null;
	}

	private void OnPhotonRandomJoinFailed()
	{
		if (chooseTypeGame.Equals(TypeGame.normal) || !chooseNameLevel.Equals(string.Empty))
		{
			createNewRoom(string.Empty, 10, string.Empty, chooseTypeGame, chooseNameLevel);
		}
		else
		{
			CreateRandomRoomForChoosedType(chooseTypeGame);
		}
	}

	private void OnJoinedRoom()
	{
		BCWDebug.Log("OnJoinedRoom");
		changeMap = false;
		if (_moveToGameScene == null)
		{
			_moveToGameScene = MoveToGameScene();
			CoroutineRunner.Instance.StartCoroutine(_moveToGameScene);
		}
	}

	private void OnCreatedRoom()
	{
		BCWDebug.Log("OnCreatedRoom");
		changeMap = false;
		if (_moveToGameScene == null)
		{
			_moveToGameScene = MoveToGameScene();
			CoroutineRunner.Instance.StartCoroutine(_moveToGameScene);
		}
	}

	private void Update()
	{
		if ((!(GameController.instance != null) || GameController.instance.curTypeGame == TypeGame.RocketLeague) && PhotonNetwork.room != null)
		{
			if ((MarketController.Instance != null && MarketController.Instance.marketOpened) || (TDMController.instance != null && !TDMController.instance.pvpStarted && GameController.instance.curTypeGame != TypeGame.race && GameController.instance.curTypeGame != 0) || (ChatController.thisScript != null && ChatController.thisScript.enabled) || (PauseWindow.instance != null && PauseWindow.instance.isShow))
			{
				PhotonNetwork.sendRate = 2;
				PhotonNetwork.sendRateOnSerialize = 2;
			}
			else
			{
				PhotonNetwork.sendRate = 10;
				PhotonNetwork.sendRateOnSerialize = 10;
			}
		}
	}

	public void createNewRoom(string NameRoom, int MaxKolPlayers, string Password, TypeGame modeGame, string nameLevel)
	{
		if (string.IsNullOrEmpty(NameRoom))
		{
			if (controllerMenu.thisScript != null)
			{
				controllerMenu.thisScript.showIndicator();
			}
			string[] customRoomPropertiesForLobby = new string[6] { "pass", "nameLevel", _minLeague, _maxLeague, _typeGame, "Boiler" };
			if (string.IsNullOrEmpty(nameLevel))
			{
				nameLevel = ((chooseTypeGame != 0) ? ManagerPVPLevels.instance.GetRandomLevel() : "Level1");
			}
			switch (modeGame)
			{
			case TypeGame.race:
				MaxKolPlayers = 5;
				break;
			case TypeGame.tanks:
				MaxKolPlayers = 10;
				break;
			case TypeGame.TDM:
				MaxKolPlayers = 14;
				break;
			case TypeGame.Zombe:
				MaxKolPlayers = settings.GetSettings(TypeGame.Zombe).maxPlayers;
				break;
			case TypeGame.CopsAndRobbers:
				MaxKolPlayers = settings.GetSettings(TypeGame.CopsAndRobbers).maxPlayers;
				break;
			case TypeGame.SkyBlock:
				MaxKolPlayers = 10;
				break;
			case TypeGame.RocketLeague:
				MaxKolPlayers = 6;
				break;
			case TypeGame.Pixelmon:
				MaxKolPlayers = 14;
				break;
			case TypeGame.WalkingRobots:
				MaxKolPlayers = 14;
				break;
			case TypeGame.normal:
				MaxKolPlayers = 15;
				break;
			default:
				MaxKolPlayers = 10;
				break;
			}
			ExitGames.Client.Photon.Hashtable hashtable = new ExitGames.Client.Photon.Hashtable();
			hashtable["pass"] = Password;
			hashtable["nameLevel"] = nameLevel;
			hashtable[_typeGame] = (int)modeGame;
			controllerLoadingGame.typeGame = modeGame;
			if ((modeGame == TypeGame.race || modeGame == TypeGame.RocketLeague) && CarBoiler.ContainsKey(settings.RaceCarName))
			{
				hashtable["Boiler"] = CarBoiler[settings.RaceCarName];
				BCWDebug.LogError("createNewRoom: " + settings.RaceCarName + " " + CarBoiler[settings.RaceCarName]);
			}
			if (nameLevel.Equals("Level1"))
			{
				hashtable[_minLeague] = sandboxBoilers[_playerSandboxBoiler].minLvl.ToString();
				hashtable[_maxLeague] = sandboxBoilers[_playerSandboxBoiler].maxLvl.ToString();
				hashtable[_respZone] = BCWStorage.Get<string>(settings.keyNameArea);
			}
			else
			{
				hashtable[_minLeague] = Boilers[_playerBoiler].minLvl.ToString();
				hashtable[_maxLeague] = Boilers[_playerBoiler].maxLvl.ToString();
			}
			RoomOptions roomOptions = new RoomOptions();
			roomOptions.isVisible = false;
			roomOptions.isOpen = true;
			roomOptions.maxPlayers = (byte)MaxKolPlayers;
			roomOptions.customRoomProperties = hashtable;
			roomOptions.customRoomPropertiesForLobby = customRoomPropertiesForLobby;
			if (BCWDebug.isDebugBuild)
			{
				BCWDebug.Log("createNewRoom modeGame=" + modeGame.ToString() + " Level=" + nameLevel);
			}
			if (NameRoom != null && (NameRoom == string.Empty || NameRoom == " "))
			{
				NameRoom = null;
			}
			PhotonNetwork.CreateRoom(NameRoom, roomOptions, null);
		}
		else if (controllerMenu.thisScript != null)
		{
			controllerMenu.thisScript.showMessage("This name already exists.");
		}
	}

	private bool roomWithNameCreate(string nameRoom)
	{
		foreach (RoomInfo filteredRoom in filteredRoomList)
		{
			if (filteredRoom.name == nameRoom)
			{
				return true;
			}
		}
		return false;
	}

	public void joinRoomName(string name)
	{
		if (controllerMenu.thisScript != null)
		{
			BCWDebug.Log("joinRoomName");
			controllerMenu.thisScript.showIndicator();
		}
		settings.offlineMode = false;
		PhotonNetwork.JoinRoom(name);
	}

	public void OnReceivedRoomListUpdate()
	{
	}

	public RoomLevels GetPlayerBoiler()
	{
		return Boilers[_playerBoiler];
	}

	public void OnReceivedRoomList()
	{
	}

	private IEnumerator MoveToGameScene()
	{
		BCWDebug.Log("MoveToGameScene");
		while (PhotonNetwork.room == null)
		{
			yield return 0;
		}
		if (PhotonNetwork.room.playerCount == PhotonNetwork.room.maxPlayers + 1)
		{
			controllerMenu.thisScript.showMessage("This room is full. Please, try another room!");
			yield break;
		}
		Save.SaveString(settings.keyRoomName, PhotonNetwork.room.name);
		Save.SaveString(settings.keyRoomPass, PhotonNetwork.room.customProperties["pass"].ToString());
		settings.keySelectScene = PhotonNetwork.room.customProperties[_nameLevel].ToString();
		TypeGame typeGame = (TypeGame)(int)PhotonNetwork.room.customProperties[_typeGame];
		string imageNameGorLoading = string.Empty;
		if (typeGame != 0 && typeGame != TypeGame.TDM)
		{
			settings.SetAreaNameForLoading(settings.keySelectScene);
		}
		else if (typeGame == TypeGame.TDM)
		{
			settings.SetAreaNameForLoading("RaceTrack3");
		}
		else
		{
			imageNameGorLoading = BCWStorage.Get<string>(settings.keyForShowLoadingSprite);
		}
		PlayerPrefs.Save();
		PhotonNetwork.isMessageQueueRunning = false;
		bool offline = !controllerConnectGame.reconnectRoom || (GameController.instance != null && GameController.instance.curTypeGame == TypeGame.CopsAndRobbers);
		if (GameController.instance != null && GameController.instance.myPlayer != null && offline)
		{
			SceneManager.UnloadScene("Lods_Level_1");
			SceneManager.UnloadScene("Level1_OfflineAdditive");
			GameController.instance.removePlayerFromList(GameController.instance.playerScript);
			Object.Destroy(GameController.instance.myPlayer);
		}
		AsyncOperation async3 = null;
		if (SceneManager.GetActiveScene().name != PhotonNetwork.room.customProperties[_nameLevel].ToString() || offline)
		{
			async3 = SceneManager.LoadSceneAsync("LoadingGame");
			while (!async3.isDone)
			{
				yield return null;
			}
		}
		if (PhotonNetwork.room.customProperties.ContainsKey(_indexRound) && GameController.instance != null && (GameController.instance.curTypeGame == TypeGame.TitanfallV2 || GameController.instance.curTypeGame == TypeGame.WalkingRobots) && PhotonNetwork.room.customProperties[_indexRound].ToString() != controllerConnectGame.thisScript.reconnectRoundIndex.ToString())
		{
			async3 = SceneManager.LoadSceneAsync("LoadingGame");
			while (!async3.isDone)
			{
				yield return null;
			}
		}
		settings.updateOfflineMode(false);
		while (SceneManager.GetActiveScene().name != PhotonNetwork.room.customProperties[_nameLevel].ToString())
		{
			yield return null;
		}
		BCWDebug.Log("Scene " + SceneManager.GetActiveScene().name + " " + PhotonNetwork.room.customProperties[_nameLevel]);
		chooseTypeGame = typeGame;
		chooseNameLevel = PhotonNetwork.room.customProperties[_nameLevel].ToString();
		FriendsController.instance.ClearBattleInvites();
		if (!PhotonNetwork.room.visible && PhotonNetwork.room.playerCount > 1 && GameController.instance.curTypeGame == TypeGame.race)
		{
			BCWDebug.Log("PhotonNetwork.room.visible " + PhotonNetwork.room.visible);
			changeMap = true;
			PhotonNetwork.isMessageQueueRunning = true;
			LeaveRoom(false);
			yield break;
		}
		changeMap = false;
		PhotonNetwork.isMessageQueueRunning = true;
		if (IOSInternetConnection.isEnable)
		{
			controllerConnectGame.thisScript.instantiateNetworkObjects(chooseTypeGame);
		}
		else
		{
			controllerConnectGame.thisScript.instantiateNetworkObjects((TypeGame)(int)PhotonNetwork.room.customProperties[_typeGame]);
		}
	}

	public void OnPhotonPlayerConnected(PhotonPlayer player)
	{
		if ((bool)FriendsUINotification.instance)
		{
			if (player == null)
			{
				BCWDebug.LogError("OnPhotonPlayerConnected PhotonPlayer IS NULL");
			}
			else if (!player.customProperties.ContainsKey(PlayerPropsKeys.playerId))
			{
				BCWDebug.LogError("OnPhotonPlayerConnected CustomProperties NOT CONTAINS KEY playerId");
			}
			else
			{
				FriendsUINotification.instance.AddInQueueJoinFriend(player.customProperties[PlayerPropsKeys.playerId].ToString());
			}
		}
	}

	public void OnPhotonPlayerDisconnected(PhotonPlayer player)
	{
		if (controllerMenu.thisScript != null)
		{
			controllerMenu.thisScript.hideIndicator();
		}
	}

	public RoomInfo GetRoomInfoByName(string RoomName)
	{
		if (_listRoom == null)
		{
			_listRoom = PhotonNetwork.GetRoomList();
		}
		for (int i = 0; i < _listRoom.Length; i++)
		{
			if (_listRoom[i].name.Equals(RoomName))
			{
				return _listRoom[i];
			}
		}
		_listRoom = PhotonNetwork.GetRoomList();
		for (int j = 0; j < _listRoom.Length; j++)
		{
			if (_listRoom[j].name.Equals(RoomName))
			{
				return _listRoom[j];
			}
		}
		return null;
	}
}
